package com.ang.threadLocal;

/**
 * @author ssang
 * @date 2023-03-09 14:13
 *
 * ThreadLocal，在set的时候，其实是获取了当前线程的threadLocals属性（ThreadLocal.ThreadLocalMap类型），并使用threadLocal作为key，把值存到threadLocals
 * 在get的时候，先获取到当前线程的threadLocals属性（ThreadLocal.ThreadLocalMap类型），再使用threadLocal作为key从map中取值
 *
 * 所以在取值的时候，要保证当前线程和treadLocal相同
 */
public class Test01 {
    public static void main(String[] args) {
        Test01 t = new Test01();
        t.test01();
        t.test02();
    }

    /**
     *
     */
    public void test01(){
        System.out.println("test01:------------------->");
        ThreadLocal threadLocal = this.save1();
        ThreadLocal threadLocal1 = this.get1();
        //false，false
        //save和get里面的threadLocal不是同一个对象，所以save中的值，在get中获取不到
        System.out.println(threadLocal==threadLocal1);
        System.out.println(threadLocal.hashCode()==threadLocal1.hashCode());
    }

    public ThreadLocal save1(){
        ThreadLocal threadLocal = new ThreadLocal();
        threadLocal.set(Thread.currentThread().getName());
        return threadLocal;
    }

    public ThreadLocal get1(){
        ThreadLocal threadLocal = new ThreadLocal();
        Object o = threadLocal.get();
        System.out.println(o);
        return threadLocal;
    }


    /**
     *
     */
    public void test02(){
        System.out.println("test02:------------------->");
        ThreadLocal threadLocal = new ThreadLocal();
        //save中和get中使用同一个threadLocal，get中能获取到save的值
        this.save2(threadLocal);
        this.get2(threadLocal);
    }

    public void save2(ThreadLocal threadLocal){
        System.out.println("save:"+Thread.currentThread().getName());
        threadLocal.set(Thread.currentThread().getName());
    }

    public void get2(ThreadLocal threadLocal){
        System.out.println(Thread.currentThread().getName());
        Object o = threadLocal.get();
        System.out.println(o);
    }
}
